package com.truckdispatching.database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseOpenHelper extends SQLiteOpenHelper {

	static final String					DATABASE_NAME		= "TruckDispatching.db";

	static final int					DATABASE_VERSION	= 1;

	public static SQLiteDatabase		mDataBase			= null;

	private static DataBaseOpenHelper	instance			= null;

	public static void initDataBaseContext(Context aContext) {
		if (instance == null) {
			instance = new DataBaseOpenHelper(aContext, DATABASE_NAME, null, DATABASE_VERSION);
		}
		if (mDataBase == null) {
			mDataBase = instance.getWritableDatabase();
		}
	}

	public static synchronized DataBaseOpenHelper getInstance() {
		return instance;
	}

	public void dataReset() {}

	private DataBaseOpenHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		NotificationSql.getInstance().createTable(db);
	}

	@Override
	protected void finalize() throws Throwable {
		close();
		super.finalize();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	/**
	 * 
	 * @param tableName
	 * @return
	 */
	public boolean exist(String tableName) {
		boolean exist = false;
		Cursor cur = null;
		try {
			StringBuilder builder = new StringBuilder("select 1 from sqlite_master where type='table' and name='");
			builder.append(tableName).append("';");
			cur = mDataBase.rawQuery(builder.toString(), null);
			if (cur.moveToFirst()) {
				if (cur.getInt(0) == 1) {
					exist = true;
				}
			}
		} finally {
			if (cur != null) {
				cur.close();
			}
		}

		return exist;
	}

	public void deleteAllData() {
		try {

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void close() {
		try {
			if (mDataBase != null) {
				mDataBase.close();
				mDataBase = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
